package com.rzico.sbl.ui.report.manager

import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import com.github.mikephil.charting.animation.Easing
import com.github.mikephil.charting.data.PieEntry
import com.lzy.okgo.model.HttpMethod
import com.rzico.sbl.R
import com.rzico.sbl.databinding.FragmentManagerFirstBinding
import com.rzico.sbl.other.*
import com.rzico.sbl.ui.report.other.ReportUrl
import com.rzico.sbl.viewmodel.ReportManagerViewModel
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.floatValue
import com.xinnuo.common_ui.base.NavigationFragment
import org.json.JSONObject

class ManagerFirstFragment : NavigationFragment() {

    private var mBinding: FragmentManagerFirstBinding? = null

    private var mInBeginDate = getBeforeDate(6)
    private var mInEndDate = getTodayDate()
    private var mOutBeginDate = getBeforeDate(6)
    private var mOutEndDate = getTodayDate()
    private var mWayBeginDate = getBeforeDate(6)
    private var mWayEndDate = getTodayDate()

    override fun getViewModel() = get<ReportManagerViewModel>()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ) = FragmentManagerFirstBinding
        .inflate(inflater, container, false)
        .also { mBinding = it }
        .root

    override fun initTitle() {
        initListener()

        mBinding?.let {
            it.managerChart1.initChart()
            it.managerChart2.initChart()
            it.managerChart3.initChart()
        }
    }

    private fun initListener() {
        mBinding?.apply {
            managerInAll.oneClick { startActivityEx<ReportIncomeActivity>() }
            managerOutAll.oneClick { startActivityEx<ReportPayoutActivity>() }
            managerWayAll.oneClick { startActivityEx<ReportMethodActivity>() }

            inTime.addTimeListener { start, end, _ ->
                mInBeginDate = start
                mInEndDate = end

                getViewModel().cancelRequest()
                getInChartData()
            }

            outTime.addTimeListener { start, end, _ ->
                mOutBeginDate = start
                mOutEndDate = end

                getViewModel().cancelRequest()
                getOutChartData()
            }

            wayTime.addTimeListener { start, end, _ ->
                mWayBeginDate = start
                mWayEndDate = end

                getViewModel().cancelRequest()
                getWayChartData()
            }
        }
    }

    override fun onResume() {
        super.onResume()

        getInChartData()
        getOutChartData()
        getWayChartData()
    }

    /**
     * 设置收入饼状图数据
     */
    private fun setInChartData(
        total: Float,
        amountArray: Array<Float>
    ) {
        mBinding?.let {
            it.inTotal.text = (total > 0)
                .conditionElseValue(
                    actionTrue = { " (总: ${total.formatDecimal()})" },
                    actionFalse = { "" }
                )

            it.managerChart1.apply {
                (total > 0)
                    .conditionElse(
                        actionTrue = {
                            setCenterImage(R.mipmap.icon_report_m_06)

                            setPieData(
                                colors = getViewModel().incomeColor(),
                                formatter = null,
                                entries = arrayOf(
                                    PieEntry(amountArray[0], "商品收入"),
                                    PieEntry(amountArray[1], "押桶"),
                                    PieEntry(amountArray[2], "买桶"),
                                    PieEntry(amountArray[3], "补差价1:1")
                                )
                            )
                        },
                        actionFalse = ::clear
                    )

                animateY(1000, Easing.EaseInOutQuad)
            }
        }
    }

    /**
     * 设置支出饼状图数据
     */
    private fun setOutChartData(
        total: Float,
        amountArray: Array<Float>
    ) {
        mBinding?.let {
            it.outTotal.text = (total > 0)
                .conditionElseValue(
                    actionTrue = { " (总: ${total.formatDecimal()})" },
                    actionFalse = { "" }
                )

            it.managerChart2.apply {
                (total > 0)
                    .conditionElse(
                        actionTrue = {
                            setCenterImage(R.mipmap.icon_report_m_07)

                            setPieData(
                                colors = getViewModel().payoutColor(),
                                formatter = null,
                                PieEntry(amountArray[0], "水票抵扣"),
                                PieEntry(amountArray[1], "优惠券"),
                                PieEntry(amountArray[2], "免单"),
                                PieEntry(amountArray[3], "漏桶"),
                                PieEntry(amountArray[4], "退桶")
                            )
                        },
                        actionFalse = ::clear
                    )

                animateY(1000, Easing.EaseInOutQuad)
            }
        }
    }

    /**
     * 设置支付方式饼状图数据
     */
    private fun setWayChartData(
        total: Float,
        amountArray: Array<Float>
    ) {
        mBinding?.let {
            it.managerChart3.apply {
                (total > 0)
                    .conditionElse(
                        actionTrue = {
                            formartCenterText(
                                value = total.formatDecimalWhenHave(),
                                hint = "总金额",
                                proportion = 1.2f
                            )

                            setPieData(
                                colors = getViewModel().methodColor(),
                                formatter = null,
                                PieEntry(amountArray[0], "微信"),
                                PieEntry(amountArray[1], "支付宝"),
                                PieEntry(amountArray[2], "现金")
                            )
                        },
                        actionFalse = ::clear
                    )

                animateY(1000, Easing.EaseInOutQuad)
            }
        }
    }

    /**
     * 获取收入饼状图数据
     */
    private fun getInChartData() {
        getViewModel()
            .request(
                isLoadingBefore = false,
                isLoadingAfter = false,
                requestUrl = ReportUrl.getBaseUrl().zInSum,
                requestMethod = HttpMethod.GET,
                params = arrayOf(
                    "beginDate" to mInBeginDate,
                    "endDate" to mInEndDate
                ),
                onSuccess = {
                    val obj = JSONObject(it)

                    arrayOf(
                        obj.optNotNull("subPrice").floatValue,
                        obj.optNotNull("pledge").floatValue,
                        obj.optNotNull("buy").floatValue,
                        obj.optNotNull("differPrice").floatValue
                    ).apply {
                        setInChartData(sum(), this)
                    }
                }
            )
    }

    /**
     * 获取支出饼状图数据
     */
    private fun getOutChartData() {
        getViewModel()
            .request(
                isLoadingBefore = false,
                isLoadingAfter = false,
                requestUrl = ReportUrl.getBaseUrl().zOutSum,
                requestMethod = HttpMethod.GET,
                params = arrayOf(
                    "beginDate" to mOutBeginDate,
                    "endDate" to mOutEndDate
                ),
                onSuccess = {
                    val obj = JSONObject(it)

                    arrayOf(
                        obj.optNotNull("exchangePrice").floatValue,
                        obj.optNotNull("coupon").floatValue,
                        obj.optNotNull("free").floatValue,
                        obj.optNotNull("swap").floatValue,
                        obj.optNotNull("refunds").floatValue
                    ).apply {
                        setOutChartData(sum(), this)
                    }
                }
            )
    }

    /**
     * 获取支付方式饼状图数据
     */
    private fun getWayChartData() {
        getViewModel()
            .request(
                isLoadingBefore = false,
                isLoadingAfter = false,
                requestUrl = ReportUrl.getBaseUrl().zWaySum,
                requestMethod = HttpMethod.GET,
                params = arrayOf(
                    "beginDate" to mWayBeginDate,
                    "endDate" to mWayEndDate
                ),
                onSuccess = {
                    val obj = JSONObject(it)

                    arrayOf(
                        obj.optNotNull("weixinPay").floatValue,
                        obj.optNotNull("aliPay").floatValue,
                        obj.optNotNull("cashPay").floatValue
                    ).apply {
                        setWayChartData(sum(), this)
                    }
                }
            )
    }

    override fun onDestroyView() {
        super.onDestroyView()
        mBinding = null
    }

}